<?php
class Service extends CI_Model
{
	
	function get_all($limit=10000, $offset=0)
	{
		
		$this->db->from('services');
		/*$this->db->join('people','services.customer_id=people.person_id','left');			
		if($customer_id !=-1){}*/
			$this->db->where('delete',0);
				
		$this->db->order_by("service_id", "desc");
		$this->db->order_by("date_return", "desc");
		$this->db->limit($limit);
		$this->db->offset($offset);
		$data = array();
        $Q = $this->db->get();
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
		
	    $Q->free_result(); 
	    
	    return $data; 
	}
	
	function get_all_print($list_serv = '',$limit=10000, $offset=0)
	{
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		}else{
			$list_serv = '';
		}
		$this->db->from('services');
		$cur_date = date("Y-m-d H:i:s");
		if($list_serv != ''){
			$this->db->where_in('service_id',$list_serv);
		}else{
			$this->db->where('print','0');
		}
		$this->db->where('delete',0);		
		$this->db->order_by("service_id", "desc");
		$this->db->order_by("date_return", "desc");
		$this->db->limit($limit);
		$this->db->offset($offset);
		$data = array();
        $Q = $this->db->get();
        
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
		
	    $Q->free_result(); 
	    return $data; 
	}
	
	function getNos($list_serv = '')
	{
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		}else{
			$list_serv = '';
		}
		$this->db->from('services');
		if($list_serv != ''){
			$this->db->where_in('service_id',$list_serv);
		}
		$this->db->where('delete',0);
		$this->db->order_by("print", "desc");
		$this->db->limit(1);
		$this->db->offset(0);
		$data = array();
        $Q = $this->db->get();
        
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
		
	    $Q->free_result(); 
	    return $data; 
	}
	
	function delete($list_serv = '')
	{
		$service_data = array ('delete' => 1);
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		
			$this->db->from('services');
			$this->db->where_in('service_id',$list_serv);
	       	$Q = $this->db->update('services',$service_data);
		}
        
	    return $Q;
         
	}
	
	function count_all()
	{
		$this->db->from('services');
		$this->db->where('delete',0);
		$data = array();
        $Q = $this->db->get();
          	
	    return $Q->num_rows(); 
	}
	
	function count_all_print($list_serv)
	{
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		}else{
			$list_serv = '';
		}
		$this->db->from('services');
		$cur_date = date("Y-m-d H:i:s");
		if($list_serv != ''){
			$this->db->where_in('service_id',$list_serv);
		}else{
			$this->db->where('print','0');
		}
		$this->db->where('delete',0);
		$data = array();
        $Q = $this->db->get();
          	
	    return $Q->num_rows(); 
	}
	
	function total_cost()
	{
		$this->db->select_sum('service_cost');
		$this->db->from('services');
		$this->db->where('delete',0);
		$data = array();
        $Q = $this->db->get();
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
		
	    $Q->free_result(); 
	    
	    return $data; 
	}
	
	function total_cost_print($list_serv)
	{
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		}else{
			$list_serv = '';
		}
		$this->db->select_sum('service_cost');
		$this->db->from('services');
		$cur_date = date("Y-m-d H:i:s");
		if($list_serv != ''){
			$this->db->where_in('service_id',$list_serv);
		}else{
			$this->db->where('print','0');
		}
		$this->db->where('delete',0);
		$data = array();
        $Q = $this->db->get();
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
		
	    $Q->free_result(); 
	    
	    return $data; 
	}
	
	public function get_info($service_id)
	{
		$this->db->from('services');
		$this->db->where('delete',0);
		$this->db->where('service_id',$service_id);
		$data = array();
        $Q = $this->db->get();
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
	    $Q->free_result(); 
	    
	    return $data;
	}

	function exists($service_id)
	{
		$this->db->from('services');
		$this->db->where('service_id',$service_id);
		$query = $this->db->get();

		return ($query->num_rows()==1);
	}
	
	function update($service_data, $service_id)
	{
		
		if (!$service_id or !$this->exists($service_id))
		{
			if($this->db->insert('services',$service_data))
			{
				return true;
			}
			return false;
		}
		
		$this->db->where('service_id', $service_id);
		$success = $this->db->update('services',$service_data);
		
		return $success;
	}
	
	function update_print($service_data,$list_serv)
	{
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		}else{
			$list_serv = '';
		}
		$this->db->where('delete',0);
		if($list_serv != ''){
			$this->db->where_in('service_id',$list_serv);
		}
		$this->db->update('services',$service_data);
		return true;
	}
	function get_max_print()
	{
		$this->db->select_max('print');
		$this->db->from('services');
		$this->db->where('delete',0);
		$data = array();
        $Q = $this->db->get();
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
		
	    $Q->free_result(); 
	    
	    return $data; 
	}
	
	function update_status_after_make_receipt($service_data,$list_serv)
	{
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		}else{
			$list_serv = '';
		}
		
		if($list_serv != ''){
			$this->db->where_in('service_id',$list_serv);
		}
		$this->db->where('delete',0);
		$this->db->update('services',$service_data);
		return true;
	}
	
	function update_status($service_data,$list_serv)
	{
		if(!empty($list_serv)){
			$list_serv = explode(',', $list_serv);
		}else{
			$list_serv = '';
		}
		
		if($list_serv != ''){
			$this->db->where_in('service_id',$list_serv);
		}
		$this->db->where('delete',0);
		$this->db->update('services',$service_data);
		return true;
	}
	
	public function update_none_cus($customer_id)
	{
		$serv_data['customer_id'] = $customer_id;
		$array = array('customer_id' => '0');
		$this->db->where($array);
		$this->db->where('delete',0);
		$this->db->update('services',$serv_data);
		return true;
	}
	
	function save ($items,$customer_id,$employee_id,$comment,$payments,$sale_id=false)
	{
		if(count($items)==0)
			return -1;

		$payment_types='';
		foreach($payments as $payment_id=>$payment)
		{
			$payment_types=$payment_types.$payment['payment_type'].': '.to_currency($payment['payment_amount']).'<br />';
		}

		$sales_data = array(
			'sale_time' => date('Y-m-d H:i:s'),
			'customer_id'=> $this->Customer->exists($customer_id) ? $customer_id : null,
			'employee_id'=>$employee_id,
			'payment_type'=>$payment_types,
			'comment'=>$comment
		);

		//Run these queries as a transaction, we want to make sure we do all or nothing
		$this->db->trans_start();

		$this->db->insert('sales',$sales_data);
		$sale_id = $this->db->insert_id();

		foreach($payments as $payment_id=>$payment)
		{
			if ( substr( $payment['payment_type'], 0, strlen( lang('sales_giftcard') ) ) == lang('sales_giftcard') )
			{
				/* We have a gift card and we have to deduct the used value from the total value of the card. */
				$splitpayment = explode( ':', $payment['payment_type'] );
				$cur_giftcard_value = $this->Giftcard->get_giftcard_value( $splitpayment[1] );
				$this->Giftcard->update_giftcard_value( $splitpayment[1], $cur_giftcard_value - $payment['payment_amount'] );
			}

			$sales_payments_data = array
			(
				'sale_id'=>$sale_id,
				'payment_type'=>$payment['payment_type'],
				'payment_amount'=>$payment['payment_amount']
			);
			$this->db->insert('sales_payments',$sales_payments_data);
		}

		foreach($items as $line=>$item)
		{
			if (isset($item['item_id']))
			{
				$cur_item_info = $this->Item->get_info($item['item_id']);

				$sales_items_data = array
				(
					'sale_id'=>$sale_id,
					'item_id'=>$item['item_id'],
					'line'=>$item['line'],
					'description'=>$item['description'],
					'serialnumber'=>$item['serialnumber'],
					'quantity_purchased'=>$item['quantity'],
					'discount_percent'=>$item['discount'],
					'item_cost_price' => $cur_item_info->cost_price,
					'item_unit_price'=>$item['price']
					);

				$this->db->insert('sales_items',$sales_items_data);

				//Update stock quantity
				$item_data = array('quantity'=>$cur_item_info->quantity - $item['quantity']);
				$this->Item->save($item_data,$item['item_id']);
			
				//Ramel Inventory Tracking
				//Inventory Count Details
				$qty_buy = -$item['quantity'];
				$sale_remarks ='POS '.$sale_id;
				$inv_data = array
				(
					'trans_date'=>date('Y-m-d H:i:s'),
					'trans_items'=>$item['item_id'],
					'trans_user'=>$employee_id,
					'trans_comment'=>$sale_remarks,
					'trans_inventory'=>$qty_buy
					);
				$this->Inventory->insert($inv_data);
			}
			else
			{
				$cur_item_kit_info = $this->Item_kit->get_info($item['item_kit_id']);

				$sales_item_kits_data = array
				(
					'sale_id'=>$sale_id,
					'item_kit_id'=>$item['item_kit_id'],
					'line'=>$item['line'],
					'description'=>$item['description'],
					'quantity_purchased'=>$item['quantity'],
					'discount_percent'=>$item['discount'],
					'item_kit_cost_price' => $cur_item_kit_info->cost_price,
					'item_kit_unit_price'=>$item['price']
				);

				$this->db->insert('sales_item_kits',$sales_item_kits_data);
				
				foreach($this->Item_kit_items->get_info($item['item_kit_id']) as $item_kit_item)
				{
					$cur_item_info = $this->Item->get_info($item_kit_item->item_id);
					
					//Update stock quantity
					$item_data = array('quantity'=>$cur_item_info->quantity - ($item['quantity'] * $item_kit_item->quantity));
					$this->Item->save($item_data,$item_kit_item->item_id);

					//Ramel Inventory Tracking
					//Inventory Count Details
					$qty_buy = -$item['quantity'] * $item_kit_item->quantity;
					$sale_remarks ='POS '.$sale_id;
					$inv_data = array
					(
						'trans_date'=>date('Y-m-d H:i:s'),
						'trans_items'=>$item_kit_item->item_id,
						'trans_user'=>$employee_id,
						'trans_comment'=>$sale_remarks,
						'trans_inventory'=>$qty_buy
						);
					$this->Inventory->insert($inv_data);					
				}
			}
			
			$customer = $this->Customer->get_info($customer_id);
 			if ($customer_id == -1 or $customer->taxable)
 			{
				if (isset($item['item_id']))
				{
					foreach($this->Item_taxes->get_info($item['item_id']) as $row)
					{
						$this->db->insert('sales_items_taxes', array(
							'sale_id' 	=>$sale_id,
							'item_id' 	=>$item['item_id'],
							'line'      =>$item['line'],
							'name'		=>$row['name'],
							'percent' 	=>$row['percent'],
							'cumulative'=>$row['cumulative']
						));
					}
				}
				else
				{
					foreach($this->Item_kit_taxes->get_info($item['item_kit_id']) as $row)
					{
						$this->db->insert('sales_item_kits_taxes', array(
							'sale_id' 		=>$sale_id,
							'item_kit_id'	=>$item['item_kit_id'],
							'line'      	=>$item['line'],
							'name'			=>$row['name'],
							'percent' 		=>$row['percent'],
							'cumulative'	=>$row['cumulative']
						));
					}					
				}
			}
		}
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE)
		{
			return -1;
		}
		
		return $sale_id;
	}

	/*function search($search, $limit=20)
	{
		$this->db->from('service');
		$this->db->where("(print LIKE '%".$this->db->escape_like_str($search)."%'");
		$this->db->order_by("print", "asc");
		$this->db->limit($limit);
		return $this->db->get();	
	}*/
	
	function search($search,$limit=10000, $offset=0)
	{
		$data = array();
		if(empty($data)){
			$this->db->from('services');
			if(!empty($search)){
				$this->db->where('print',$search);
			}	
			$this->db->where('delete',0);
			$this->db->order_by("service_id", "desc");
			$this->db->order_by("date_return", "desc");
			$this->db->limit($limit);
			$this->db->offset($offset);
			$data = array();
	        $Q = $this->db->get();
	        if ($Q->num_rows() > 0){
		       	foreach ($Q->result_array() as $row){
		         	$data[] = $row;
		       	}
	        }
		}
		
	    if(empty($data)){
		    $this->db->from('services');
			if(!empty($search)){
				$this->db->where('customer_name',$search);
			}	
			$this->db->where('delete',0);
			$this->db->order_by("service_id", "desc");
			$this->db->order_by("date_return", "desc");
			$this->db->limit($limit);
			$this->db->offset($offset);
			$data = array();
	        $Q = $this->db->get();
	        if ($Q->num_rows() > 0){
		       	foreach ($Q->result_array() as $row){
		         	$data[] = $row;
		       	}
	        }	
	    }
	    
		if(empty($data)){
		    $this->db->from('services');
			if(!empty($search)){
				$this->db->where('phone_num',$search);
			}	
			$this->db->where('delete',0);
			$this->db->order_by("service_id", "desc");
			$this->db->order_by("date_return", "desc");
			$this->db->limit($limit);
			$this->db->offset($offset);
			$data = array();
	        $Q = $this->db->get();
	        if ($Q->num_rows() > 0){
		       	foreach ($Q->result_array() as $row){
		         	$data[] = $row;
		       	}
	        }	
	    }
	    
	    
	    $Q->free_result(); 
	    
	    return $data; 
	}
	
	function count_search($search)
	{
		$this->db->from('services');
		$cur_date = date("Y-m-d H:i:s");
		$this->db->where('print',$search);
		$this->db->where('delete',0);
		$data = array();
        $Q = $this->db->get();
          	
	    return $Q->num_rows(); 
	}
	
	function total_cost_search($search)
	{
		$this->db->select_sum('service_cost');
		$this->db->from('services');
		$this->db->where('print',$search);
		$this->db->where('delete',0);
		$data = array();
        $Q = $this->db->get();
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
		
	    $Q->free_result(); 
	    
	    return $data; 
	}
	
	function get_search_suggestions($search,$limit=25)
	{
		$suggestions = array();

		$this->db->from('services');
		$this->db->where('delete',0);
		$this->db->like('customer_name', $search);
		$this->db->group_by("customer_name");
		$this->db->order_by("customer_name", "asc");
		$by_name = $this->db->get();
		foreach($by_name->result() as $row)
		{
			$suggestions[]=array('label' => $row->customer_name);
		}
		
		$this->db->from('services');
		$this->db->where('delete',0);
		$this->db->like('print', $search);
		$this->db->group_by("print");
		$this->db->order_by("print", "asc");
		$by_name = $this->db->get();
		foreach($by_name->result() as $row)
		{
			$suggestions[]=array('label' => $row->print);
		}
		
		$this->db->from('services');
		$this->db->where('delete',0);
		$this->db->like('phone_num', $search);
		$this->db->group_by("phone_num");
		$this->db->order_by("phone_num", "asc");
		$by_name = $this->db->get();
		foreach($by_name->result() as $row)
		{
			$suggestions[]=array('label' => $row->phone_num);
		}

		//only return $limit suggestions
		if(count($suggestions > $limit))
		{
			$suggestions = array_slice($suggestions, 0,$limit);
		}
		return $suggestions;

	}
	
	function insert_order($item_info,$list_make_receipt)
	{
		$list_make_receipt = explode(',', $list_make_receipt);
		foreach ($list_make_receipt as $sv){
			$service_data['service_id'] = $sv;
			$service_data['item_id'] = $item_info['item_id'];
			$service_data['name'] = $item_info['name'];
			$service_data['cost'] = $item_info['cost'];
			$service_data['quantity'] = $item_info['quantity'];
			
			$this->db->insert('phppos_services_order_items',$service_data);
		}
	}
	
	public function get_service_order_item($service_id)
	{
		$this->db->from('phppos_services_order_items');
		$this->db->where('service_id',$service_id);
		$data = array();
        $Q = $this->db->get();
        if ($Q->num_rows() > 0){
	       	foreach ($Q->result_array() as $row){
	         	$data[] = $row;
	       	}
        }
	    $Q->free_result(); 
	    
	    return $data;
	}
	
	function delete_serv_order_item($delete_array=''){
 		if($delete_array != ''){
			$this->db->where_in('id',$delete_array);
		}
		$this->db->delete('phppos_services_order_items');
		return true;
	}
}
?>
